package leeon.bbsbrower.views;

import leeon.bbsbrower.actions.BBSLogAction;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.ViewPart;

public class LoginView extends ViewPart {
	public static final String ID = "bbsbrower.view.login";
	
	private Text id = null;
	private Text pw = null;

	/**
	 * This is a callback that will allow us to create the viewer and initialize
	 * it.
	 */
	public void createPartControl(Composite parent) {
		//布局
		parent.setLayout(null);
				
		//id输入
		id = new Text(parent, SWT.BORDER);
		id.setBounds(400, 200, 200, 30);
		id.setFont(ApplicationWorkbenchWindowAdvisor.defaultFont);
		final Label idLabel = new Label(parent, SWT.NONE);
		idLabel.setText("ID:");
		idLabel.setFont(ApplicationWorkbenchWindowAdvisor.defaultFont);
		idLabel.setBounds(250, 200, 150, 30);
		
		//id窗口的回车事件，跳转到密码输入窗口
		id.addKeyListener(new KeyListener() {

			public void keyPressed(KeyEvent e) {
				if (e.keyCode == 13) {
					LoginView.this.pw.setFocus();
				}				
			}

			public void keyReleased(KeyEvent e) {}			
		});
		
		
		//密码输入
		pw = new Text(parent, SWT.BORDER|SWT.PASSWORD);
		pw.setBounds(400, 250, 200, 30);
		pw.setFont(ApplicationWorkbenchWindowAdvisor.defaultFont);
		final Label pwLabel = new Label(parent, SWT.NONE);
		pwLabel.setText("PASSWORD:");
		pwLabel.setFont(ApplicationWorkbenchWindowAdvisor.defaultFont);
		pwLabel.setBounds(250, 250, 150, 30); 
		
		
		//密码窗口的回车事件，提交登陆
		pw.addKeyListener(new KeyListener() {

			public void keyPressed(KeyEvent e) {
				if (e.keyCode == 13) {
					actionLogin();
				}
			}

			public void keyReleased(KeyEvent e) {}			
		});
	}
	
	
	/**
	 * 登陆的action
	 *
	 */
	private void actionLogin() {
		//登陆的action
		try {
			BBSLogAction.login(id.getText(), pw.getText());
		} catch (Exception e) {
			MessageDialog.openError(this.getViewSite().getShell(), "错误信息", e.toString());
			e.printStackTrace();
			return;
		}
		
		//跳转到主菜单界面
		IWorkbenchPage page = this.getViewSite().getPage();
		page.hideView(this);
		try {
			MainView main = (MainView)page.showView(MainView.ID);
			main.refreshData(0);
		} catch (PartInitException e) {
			e.printStackTrace();
		}
		
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		id.setFocus();
	}
}